//
//  HNSH_GoodsDetailViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/25.
//

#define KBottomViewHeight   55 + kBottomSafeHeight

#import "HNSH_GoodsDetailViewController.h"

//view
#import "HNSH_GoodsDetailScrollInfoCell.h"
#import "HNSH_GoodsDetailSpecCell.h"
#import "HNSH_GoodsDetailShopCell.h"
#import "HNSH_GoodsDetailImgCell.h"
#import "HNSH_GoodsDetailHeader.h"

#import "HNSH_GoodsDetailNavView.h"         //nav
#import "HNSH_GoodsDetailBottomView.h"      //bottomView
#import "HNSH_GoodsSpecView.h"              //规格

//vc
#import "HNSH_ConfirmOrderViewController.h"         //确认订单
#import "HNSH_ShopDetailViewController.h"           //商铺详情

@interface HNSH_GoodsDetailViewController ()

/* topNavView */
@property (nonatomic, strong) HNSH_GoodsDetailNavView *topNavView;

/* bottomView */
@property (nonatomic, strong) HNSH_GoodsDetailBottomView *bottomView;

/* detailModel */
@property (nonatomic, strong) HNSH_GoodsDetailModel *detailModel;

//选完规格
/** */
@property (nonatomic, assign)NSInteger type;
/** */
@property (nonatomic, assign)NSInteger count;
/** */
@property (nonatomic, strong)HNSH_GoodsSpecListItem * specItemModel;

@end

static NSString *HNSH_GoodsDetailScrollInfoCellID = @"HNSH_GoodsDetailScrollInfoCellID";
static NSString *HNSH_GoodsDetailSpecCellID = @"HNSH_GoodsDetailSpecCellID";
static NSString *HNSH_GoodsDetailShopCellID = @"HNSH_GoodsDetailShopCellID";
static NSString *HNSH_GoodsDetailImgCellID = @"HNSH_GoodsDetailImgCellID";
static NSString *HNSH_GoodsDetailHeaderID = @"HNSH_GoodsDetailHeaderID";

@implementation HNSH_GoodsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configTableView];
    
    [self configTopNav];
    
    [self configBottomView];
    
    [self loadGoodsDetail];
    
//    [self loadUserConsumeQuota];
}

- (void)configTopNav {
    [self.view addSubview:self.topNavView];
    WeakSelf(weakSelf);
    //返回
    self.topNavView.backBlock = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    self.topNavView.likeBlock = ^{
        [weakSelf loadGoodsFavoriteOperate];
    };
    self.topNavView.shareBlock = ^{
        
    };
}

- (void)configBottomView {
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(KBottomViewHeight);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    WeakSelf(weakSelf);
    self.bottomView.addCartBlock = ^{
        [weakSelf addCart];
    };
    self.bottomView.buyBlock = ^{
        [weakSelf buy];
    };
}

- (void)configTableView {
    self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    self.tableView.backgroundColor = [UIColor appWhiteLabelColor];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, KBottomViewHeight, 0));
    }];
    
    [self.tableView registerClass:[HNSH_GoodsDetailScrollInfoCell class] forCellReuseIdentifier:HNSH_GoodsDetailScrollInfoCellID];
    [self.tableView registerClass:[HNSH_GoodsDetailSpecCell class] forCellReuseIdentifier:HNSH_GoodsDetailSpecCellID];
    [self.tableView registerClass:[HNSH_GoodsDetailShopCell class] forCellReuseIdentifier:HNSH_GoodsDetailShopCellID];
    [self.tableView registerClass:[HNSH_GoodsDetailImgCell class] forCellReuseIdentifier:HNSH_GoodsDetailImgCellID];
    
    [self.tableView registerClass:[HNSH_GoodsDetailHeader class] forHeaderFooterViewReuseIdentifier:HNSH_GoodsDetailHeaderID];
}

//MARK: 加入购物车
- (void)addCart {
    if (!self.specItemModel) {
        [self loadGoodsSpec];
        return;
    }
    [HNSH_ShopNetServer requestGoodsCartAddWithSpec_id:self.specItemModel.uid quantity:[NSString stringWithFormat:@"%ld",self.count] success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"加入购物车成功"];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 购买
- (void)buy{
    if (!self.specItemModel) {
        [self loadGoodsSpec];
        return;
    }
    if ([self.detailModel.seckill_info.start_time isNotBlank] && [self.detailModel.seckill_info.uid integerValue] > 0) {//是秒杀商品
        //秒杀商品不在秒杀时间内,不能立即购买
        if ([NSString getNowTimeTimestamp].integerValue/1000 < [self.detailModel.seckill_info.start_time integerValue] || [NSString getNowTimeTimestamp].integerValue/1000 > [self.detailModel.seckill_info.end_time integerValue]) {//活动未开始--活动已结束
            [self.view makeToast:@"不在秒杀活动时间内"];
            return;
        }
    }
    HNSH_ConfirmOrderViewController * vc = [HNSH_ConfirmOrderViewController new];
    vc.goods_id = self.goodsId;
    vc.spec_id = self.specItemModel.uid;
    vc.quantity = self.count;
    vc.payment_type = self.type;
    [self.navigationController pushViewController:vc animated:YES];
}


//MARK: 弹出规格
- (void)showSpecViewWithModel:(HNSH_GoodsSpecModel *)specModel{
    WeakSelf(weakSelf);
    [HNSH_GoodsSpecView showSpecificationViewWithSpecModel:specModel goodsDetail:self.detailModel block:^(NSInteger type, NSInteger count, HNSH_GoodsSpecListItem * _Nonnull specItemModel) {
        weakSelf.type = type;
        weakSelf.count = count;
        weakSelf.specItemModel = specItemModel;
        [weakSelf.tableView reloadData];
        if (type == 1) {
            //选择完成后 进入订单页面
            [weakSelf buy];
        } else {
            //加入购物车
            [weakSelf addCart];
        }
    }];
}

#pragma mark networking
//商品详情
- (void)loadGoodsDetail {
    [HNSH_ShopNetServer requestGoodsDetailWithGoodsId:self.goodsId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            self.detailModel = [HNSH_GoodsDetailModel yy_modelWithDictionary:responseObject.resultset];
            self.bottomView.moneyString = self.detailModel.reward_amount;
            self.topNavView.favoriteAble = self.detailModel.favorite_status;
            [self.tableView reloadData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

////消费额度信息
//- (void)loadUserConsumeQuota {
//    [HNSH_ShopNetServer requestUserConsumeQuotaSuccess:^(ST_BaseNetModel * _Nullable responseObject) {
//        if (responseObject.code == 0) {
//            HNSH_GoodsDetailScrollInfoCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0 ]];
//            cell.xfedTimeLabel.text = [NSString stringWithFormat:@"额度更新时间：%@",responseObject.resultset[@"consume_quota_reset_time"]];
//            cell.xfedTitleLabel.text = [NSString stringWithFormat:@"消费额度：%.2f",[responseObject.resultset[@"consume_quota"] doubleValue]];
//            cell.xfedTitleLabel.attributedText = [ST_AttributeLabelTool handleLabelWithContent:cell.xfedTitleLabel.text SelectContent:@"消费额度：" CommonFont:cell.xfedTitleLabel.font SpeFont:cell.xfedTitleLabel.font Color:[UIColor appBlackLabelColor]];
//        }
//    } Failure:^(NSError * _Nullable error) {
//        
//    }];
//}

//规格
- (void)loadGoodsSpec {
    if (![ST_UserManager alreadyLogin]) {
        [ST_UserManager gotoLogin];
        return;
    }
    [HNSH_ShopNetServer requestGoodsSpecWithGoodsId:self.goodsId success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            HNSH_GoodsSpecModel *model = [HNSH_GoodsSpecModel yy_modelWithDictionary:responseObject.resultset];
            model.goods_type = self.detailModel.goods_type;
            [self showSpecViewWithModel:model];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//收藏
- (void)loadGoodsFavoriteOperate {
    NSString * operateType = self.detailModel.favorite_status ? @"0" : @"1";
    [HNSH_ShopNetServer requestGoodsFavoriteOperateWithGoodsId:self.goodsId operateType:operateType success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            self.detailModel.favorite_status = !self.detailModel.favorite_status;
            self.topNavView.favoriteAble = self.detailModel.favorite_status;
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

#pragma mark lazy
- (HNSH_GoodsDetailNavView *)topNavView {
    if (!_topNavView) {
        _topNavView = [[HNSH_GoodsDetailNavView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kNavBarAndStatusBarHeight)];
    }
    return _topNavView;
}

- (HNSH_GoodsDetailBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[HNSH_GoodsDetailBottomView alloc]init];
    }
    return _bottomView;
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }
    return self.detailModel.content_list.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 65.0f;
    }
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        HNSH_GoodsDetailHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HNSH_GoodsDetailHeaderID];
        return header;
    }
    return [UIView new];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return UITableViewAutomaticDimension;
        } else {
            return 50;
        }
    }
    HNSH_GoodsDetailImgInfoModel *item = self.detailModel.content_list[indexPath.row];
    CGFloat w = kScreenWidth - 24;
    CGFloat h = w * item.height / item.width;
    return h;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            HNSH_GoodsDetailScrollInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_GoodsDetailScrollInfoCellID];
            cell.model = self.detailModel;
            return cell;
        } else if (indexPath.row == 1) {
            HNSH_GoodsDetailSpecCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_GoodsDetailSpecCellID];
            if (self.specItemModel && [self.specItemModel.spec_key_name isNotBlank]) {
                cell.specString = self.specItemModel.spec_key_name;
            }
            return cell;
        } else if (indexPath.row == 2) {
            HNSH_GoodsDetailShopCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_GoodsDetailShopCellID];
            if ([self.detailModel.shop_name isNotBlank]) {
                cell.shopName = self.detailModel.shop_name;
            }
            return cell;
        }
    } else if (indexPath.section == 1) {
        HNSH_GoodsDetailImgInfoModel *item = self.detailModel.content_list[indexPath.row];
        HNSH_GoodsDetailImgCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_GoodsDetailImgCellID];
        [cell.imgV sd_setImageWithURL:[NSURL URLWithString:item.content]];
        return cell;
    }
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 1) {
        [self loadGoodsSpec];
    }
    if (indexPath.section == 0 && indexPath.row == 2) {
        HNSH_ShopDetailViewController *vc = [[HNSH_ShopDetailViewController alloc]init];
        vc.shopId = self.detailModel.shop_id;
        vc.shopName = self.detailModel.shop_name;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}

@end
